package org.texteasy;

import java.util.Map.Entry;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseUtils.InsertHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.BaseColumns;

public class SelectedContactsProvider extends ContentProvider {

	private static final String TAG = "SelectedContactsProvider";
	
	private static final String DATABASE_NAME = "selected_contacts";
	private static final int DATABASE_VERSION = 1;
	private DatabaseHelper dbHelper;
	

	private static class DatabaseHelper extends SQLiteOpenHelper{
		
		DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
		
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("create table selected_ids (_id integer primary key autoincrement," +
				"contactid long not null);");
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS selected_ids");
            onCreate(db);
		}
	}
	
	public static final class Constants implements BaseColumns {
		
		// This class cannot be instantiated
        private Constants() {}
		
		/**
         * The content:// style URL for this table
         */
        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/selectedcontact");
        
        /**
         * The MIME type of {@link #CONTENT_URI} providing a directory of selectedContacts.
         */
        public static final String SELECTED_CONTACT_CONTENT_TYPE = "vnd.texteasy.cursor.dir/vnd.texteasy.selectedContact";
		
        /**
         * The default sort order for this table
         */
        public static final String DEFAULT_SORT_ORDER = "contactid";
        
        
        public static final String TABLE_NAME_SELECTED_CONTACTS= "selected_ids";
        
    	public static final String COLUMN_CONTACT_ID = "contactid";
	}
	
	public static final String AUTHORITY = "org.texteasy.BulkMessenger.SelectedContacts";
	
	private static final UriMatcher sUriMatcher;
    private static final int SELECTED_CONTACTS = 	1;
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		
		if (sUriMatcher.match(uri) != SELECTED_CONTACTS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
		
		SQLiteDatabase database = dbHelper.getWritableDatabase();
    	int count = database.delete(SelectedContactsProvider.Constants.TABLE_NAME_SELECTED_CONTACTS, 
    			"1", null);
    	database.close();
    	return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
        case SELECTED_CONTACTS:
            return Constants.SELECTED_CONTACT_CONTENT_TYPE;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		
		if (sUriMatcher.match(uri) != SELECTED_CONTACTS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
		
		ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }
		
        boolean foundValue = false;
		for(Entry<String, Object> entries: values.valueSet()){
			if(!entries.getKey().startsWith(Constants.COLUMN_CONTACT_ID)){
				throw new IllegalArgumentException("Invalid key: " + entries.getKey());
			}else{
				foundValue = true;
			}
		}
		
		if(!foundValue){
			throw new IllegalArgumentException("At least one " + Constants.COLUMN_CONTACT_ID+ " value is required " +
				"to insert a selected contact");
		}
		
		SQLiteDatabase database = dbHelper.getWritableDatabase();
    	InsertHelper insertHelper = new InsertHelper(database, Constants.TABLE_NAME_SELECTED_CONTACTS);
    	database.beginTransaction();
    	try{
	    	ContentValues newValue = null;
	    	for(Entry<String, Object> entries: values.valueSet()){
	    		initialValues = new ContentValues();
	    		initialValues.put(Constants.COLUMN_CONTACT_ID, entries.getValue().toString());
	    		insertHelper.insert(initialValues);
	    	}
	    	database.setTransactionSuccessful();
    	}finally{
    		database.endTransaction();
    	}
    	
    	database.close();
		return Constants.CONTENT_URI;
	}

	@Override
	public boolean onCreate() {
		this.dbHelper = new DatabaseHelper(getContext());
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		
		switch (sUriMatcher.match(uri)) {
        case SELECTED_CONTACTS:
        	SQLiteDatabase database = dbHelper.getReadableDatabase();
        	return database.query(Constants.TABLE_NAME_SELECTED_CONTACTS, 
        			new String[]{Constants.COLUMN_CONTACT_ID}, null,null,
        			null,null,Constants.DEFAULT_SORT_ORDER);
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
		
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		
		throw new UnsupportedOperationException("SelectedContactsProvider does not support update");
	}

	static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(AUTHORITY, "selectedcontact", SELECTED_CONTACTS);
        
    }
	
}
